package levellogger

import (
	"errors"
	"fmt"
	"strings"
	"time"
)

type LevelLog uint16

const (
	UNKNOWN LevelLog = iota
	TRACE
	DEBUG
	INFO
	WARNING
	ERROR
	FATAL
)
type logger struct {

	level LevelLog
}

func parseloglevel(s string) (LevelLog,error) {
	s = strings.ToLower(s)
	switch s {
	case "trace":
		return TRACE, nil
	case "debug":
		return DEBUG, nil
	case "info":
		return INFO, nil
	case "warning":
		return WARNING, nil
	case "error":
		return ERROR, nil
	case "fatal":
		return FATAL, nil
	default:
		err := errors.New("input invalid loglevel")
		return UNKNOWN, err
	}


}

func NewLogger(levelstr string) logger {
	level, err := parseloglevel(levelstr)
	if err != nil{
		panic(err)
	}
	return logger{
		level: level,
	}
}

func (l logger)enable(loglevel LevelLog) bool {
	return loglevel >= l.level
}

func (l logger)Debug(msg string)  {
	if l.enable(DEBUG) {
		now := time.Now()
		fmt.Printf("[%s] [Debug] %s\n", now.Format("2006-01-02 15:04:05"),msg)
	}

}

func (l logger)Trace(msg string) {
	if l.enable(TRACE) {
		now := time.Now()
		fmt.Printf("[%s] [TRACE] %s\n", now.Format("2006-01-02 15:04:05"), msg)
	}
}

func (l logger)Info(msg string) {
	if l.enable(INFO) {
		now := time.Now()
		fmt.Printf("[%s] [Info] %s\n", now.Format("2006-01-02 15:04:05"), msg)
	}
}

func (l logger)Warning(msg string) {
	if l.enable(WARNING) {
		now := time.Now()
		fmt.Printf("[%s] [Warning] %s\n",  now.Format("2006-01-02 15:04:05"),msg)
	}
}

func (l logger)Error(msg string) {
	if l.enable(ERROR) {
		now := time.Now()
		fmt.Printf("[%s] [Error] %s\n", now.Format("2006-01-02 15:04:05"), msg)
	}
}

func (l logger)Fatal(msg string) {
	if l.enable(FATAL) {
		now := time.Now()
		fmt.Printf("[%s] [Fatal] %s\n", now.Format("2006-01-02 15:04:05"), msg)
	}
}